package com.jetpack.mvvm.lib.binding.base

import android.app.Activity
import android.os.Build
import androidx.activity.ComponentActivity
import androidx.lifecycle.*
import androidx.viewbinding.ViewBinding
import com.jetpack.mvvm.lib.binding.ext.observerWhenDestroyed
import com.jetpack.mvvm.lib.binding.ext.registerLifecycleBelowQ
import kotlin.properties.ReadOnlyProperty

abstract class ActivityDelegate<T : ViewBinding>(
    activity: Activity
) : ReadOnlyProperty<Activity, T> {
    protected var viewBinding: T? = null

    init {
        when (activity) {
            is ComponentActivity -> activity.lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    destroyed()
                }
            })
            else -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    activity.observerWhenDestroyed { destroyed() }
                }
            }
        }
    }

    fun addLifecycleFragment(activity: Activity) {
        activity.registerLifecycleBelowQ {
            destroyed()
        }
    }

    private fun destroyed() {
        viewBinding = null
    }
}